import {
  Text,
  View,
  StyleSheet,
  TouchableHighlight,
  ScrollView,
  PixelRatio, ListView
} from 'react-native'

import React, { Component } from 'react'
import Plugin from '../../Plugin'

export default class Console extends Plugin {
  static cachedLogger = []
  static LOG_TYPE = {
    LOG: 1,
    WARNING: 2,
    ERROR: 3
  }
  static theme = {
    borderColorGray: '#BBC',
    borderColor: '#DDD'
  }

  setup () {
    console.log('before Console setup')
    const log = window.console.log

    window.console.log = (msg) => {
      const callstack = new Error('').stack
      let caller
      const callstackArr = callstack.split(' at ')
      if (callstack && callstackArr.length >= 2) {
        caller = callstackArr[2].split(' ')[0]
      }
      const logMsg = this.everyTypeToString(msg)
      Console.cachedLogger.push({
        ts: new Date().getTime(),
        msg: logMsg,
        type: Console.LOG_TYPE.LOG,
        caller
      })
      log(logMsg)
      log(Console.cachedLogger)
    }
  }

  everyTypeToString (val) {
    if (val !== null && typeof val === 'object') {
      return this.strongJSONStringify(val)
    } else {
      return val
    }
  }

  strongJSONStringify (obj) {
    const seen = []
    return JSON.stringify(obj, (key, val) => {
      if (val !== null && typeof val === 'object') {
        if (seen.indexOf(val) >= 0) {
          return
        }
        seen.push(val)
      }
      return val
    })
  }

  render () {
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
    const self = this
    return (
      <View
        style={{
          flex: 1,
          backgroundColor: '#FFFFFF',
        }}>
        <View style={{flex: 1}}>
          <ListView
            dataSource={ds.cloneWithRows(Console.cachedLogger.reverse())}
            enableEmptySections={true}
            renderRow={(log) => {
              const date = new Date(log.ts)
              const formattedDate = `${date.getMonth()}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
              return (
                <TouchableHighlight
                  underlayColor={'#EEE'}
                  onPress={() => {
                    this._onPressLog.bind(this)(log)
                  }}>
                  <View
                    style={{
                      borderBottomWidth: 1 / PixelRatio.get(),
                      paddingTop: 5,
                      paddingBottom: 5,
                      flexDirection: 'row',
                      paddingLeft: 5,
                      borderColor: Console.theme.borderColorGray
                    }}>
                    <Text style={{flex: 1}}>
                      <Text
                        style={{color: 'green'}}>{formattedDate}</Text>
                      <Text
                        style={{flex: 1}}>{log.msg}</Text>
                      <Text
                        style={{color: '#AAA'}}> {log.caller || ''}</Text>
                    </Text>
                  </View>
                </TouchableHighlight>
              )
            }}
          />
        </View>

        <View
          style={{
            height: 45,
            alignSelf: 'stretch',
            borderTopWidth: 1 / PixelRatio.get(),
            borderColor: Console.theme.borderColorGray,
            flexDirection: 'row'
          }}>
          <TouchableHighlight
            onPress={this._onPressClean.bind(this)}
            underlayColor={'#EEE'}
            style={{
              flex: 1,
            }}>
            <View
              style={{
                justifyContent: 'center',
                alignItems: 'center',
                borderColor: Console.theme.borderColorGray,
                flex: 1
              }}>
              <Text style={{
                color: '#414951',
              }}>Upload</Text>
            </View>
          </TouchableHighlight>
          <View
            style={{
              width: 0,
              borderRightWidth: 1 / PixelRatio.get(),
              borderColor: Console.theme.borderColorGray,
            }}/>
          <TouchableHighlight
            onPress={this._onPressUpload.bind(this)}
            underlayColor={'#EEE'}
            style={{
              flex: 1,
            }}>
            <View
              style={{
                justifyContent: 'center',
                alignItems: 'center',
                borderColor: Console.theme.borderColorGray,
                flex: 1
              }}>
              <Text
                style={{
                  color: '#414951',
                }}>Clean</Text>
            </View>
          </TouchableHighlight>
        </View>
      </View>
    )
  }

  _onPressLog () {
  }

  _onPressUpload () {

  }

  _onPressClean () {

  }
}

const styles = StyleSheet.create({
  button: {
    justifyContent: 'center',
    alignItems: 'center',
    borderColor: Console.theme.borderColorGray,
    flex: 1
  },
  buttonText: {}
})
